// document.write("<script src='layim1/build/layui.js'></script>");


!function (win) {
    //引入js,css
    let jsPaths = [
        'layim/src/layui.js',
        'js/fingerprint2.min.js',
        'js/common.js',
        'js/config.js',
        'js/socket.io.js',
    ], cssPaths = [
        'layim/src/css/layui.css'
    ], getPath = (function () {
        let scripts = document.scripts;
        let src = scripts[scripts.length - 1].src;
        return src.substring(0, src.lastIndexOf('/') + 1);
    })();
    for (let path of cssPaths) {
        document.write("<link rel='stylesheet' href='" + getPath + path + "'>");
    }
    for (let path of jsPaths) {
        document.write("<script src='" + getPath + path + "'><\/script>");
    }

    window.onload = function () {
        layui.use(['layim', 'layer'], function (layim) {
            //检查浏览器指纹
            let $ = layui.jquery, identity = common.getFingerprint(), layer = layui.layer;
            if (!identity) {
                layer.confirm('答应我，使用正常浏览器访问好吗？', {
                    title: '检测到错误！',
                    icon: 5,
                    btn: ['好', '不好'] //按钮
                }, function () {
                    layer.msg('快去下载谷歌浏览器吧！', {icon: 1});
                }, function () {
                    layer.msg('对方不想和你说话并把你传送到了百度！', function () {
                        window.location = 'https://www.baidu.com';
                    });
                });
                return;
            }

            //layim初始化配置
            let layImConfig = {
                //初始化接口
                init: {
                    url: globalConfig.routes.init
                    , data: {}
                }
                //查看群员接口
                , members: {
                    url: globalConfig.routes.members
                    , data: {}
                }
                , uploadImage: {
                    url: globalConfig.routes.uploadImage //（返回的数据格式见下文）
                    , type: '' //默认post
                }
                , uploadFile: {
                    url: globalConfig.routes.uploadFile //（返回的数据格式见下文）
                    , type: '' //默认post
                }
                , isAudio: true //开启聊天工具栏音频
                , isVideo: true //开启聊天工具栏视频
                , tool: [{alias: 'code', title: '代码', icon: '&#xe64e;'}]//扩展工具栏
                , brief: false //简约模式（不显示主面板）
                , title: 'WebIM' //自定义主面板最小化时的标题
                , right: '100px' //主面板相对浏览器右侧距离
                , minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
                , initSkin: '5.jpg' //1-5 设置初始背景
                , skin: [] //新增皮肤
                , isfriend: true //是否开启好友
                , isgroup: true //是否开启群组
                , voice: false //声音提醒，默认开启，声音文件为：default.mp3
                , min: false //是否始终最小化主面板（默认false）

                , msgbox: '/im/layim/src/css/modules/layim/html/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
                , find: '/im/layim/src/css/modules/layim/html/find.html' //发现页面地址，若不开启，剔除该项即可
                , chatLog: '/im/html/chatlog.html' //聊天记录页面地址，若不开启，剔除该项即可
            };
            //合并配置文件的配置并初始化layim
            layim.config($.extend({}, layImConfig, globalConfig.layim));

            //监听在线状态的切换事件
            layim.on('online', function (data) {
                common.ajax(globalConfig.routes.online, 'post', {online: data}, function (res) {});
            });

            //监听签名修改
            layim.on('sign', function (value) {
                common.ajax(globalConfig.routes.sign, 'post', {sign: value}, function (res) {
                });
            });
            //监听自定义工具栏点击，以添加代码为例
            layim.on('tool(code)', function (insert) {
                layer.prompt({
                    title: '插入代码'
                    , formType: 2
                    , shade: 0
                }, function (text, index) {
                    layer.close(index);
                    insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
                });
            });

            //延迟1秒，先注册用户再去连接socket，防止socket连接时用户未注册
            let sleep = function (time) {
                let startTime = new Date().getTime() + parseInt(time, 10);
                while (new Date().getTime() < startTime) {
                }
            };
            sleep(1000); // 延时函数，单位ms


            //建立websocket
            let socket = io(globalConfig.websocket.ws, {transports: ["websocket"]});

            socket.on('connect', function () {
                common.msg("连接成功");
                common.msg("发送登录请求");
                socket.emit('login', {identity: common.getFingerprint()}, function (data) {
                });
            });
            socket.on('disconnect', function () {
                common.msg("与服务器断开", true);
            });
            socket.on('reconnecting', function () {
                common.msg("服务器已断开正在重连...", true);
            });
            socket.on('reconnect', function () {
                common.msg("重新连接成功", true);
            });
            socket.on('error', function () {
                common.msg("连接服务器失败", true);
            });

            common.socketOn(socket, 'login', function (data) {})
            //群聊成员上线
            common.socketOn(socket, 'group_online', function (data) {
                layim.getMessage({
                    system: true
                    , id: data.id
                    , type: "group"
                    , content: data.content
                });
            })
            //监听发送消息
            layim.on('sendMessage', function (res) {
                socket.emit('chatMessage', {
                    type: res.to.type,
                    send_id: res.mine.id,
                    to_id: res.to.id,
                    content: res.mine.content
                });
            })
            //监听收到消息
            common.socketOn(socket, 'chatMessage', function (data) {
                layim.getMessage(data);
            })


        });
    }


}(window)


